package com.abu.edums.controller;


import com.abu.edums.client.VodClient;
import com.abu.pojo.Chapter;
import com.abu.pojo.Video;
import com.abu.edums.service.VideoService;
import com.abu.vo.ChapterVO;
import com.abu.edums.service.ChapterService;
import com.abu.utils.Resp;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author 阿布
 * @since 2020-06-18
 */
@RestController
@RequestMapping("/eduservice/chapter")
public class ChapterController {


    @Autowired
    private ChapterService chapterService;
    @Autowired
    private VideoService videoService;
    @Autowired
    private VodClient vodClient;

    @GetMapping("getChapterVideo/{courseId}")
    public Resp queryAll(@PathVariable("courseId") String cid) {
        List<ChapterVO> chapterVOList = this.chapterService.queryChapterAndBar(cid);
//        if (CollectionUtils.isEmpty(chapterVOList)) {
//            return null;
//        }
        return Resp.ok().data("allChapterVideo", chapterVOList);
    }

    @PostMapping("addChapter")
    public Resp addChapter(@RequestBody Chapter chapter) {
        boolean flag = this.chapterService.save(chapter);
        if (flag) {
            return Resp.ok();
        }
        return Resp.error();
    }

    @GetMapping("getChapterInfo/{chapterId}")
    public Resp getChapterInfo(@PathVariable("chapterId") String chapterId) {
        Chapter chapter = this.chapterService.getById(chapterId);
        if (chapter != null) {
            return Resp.ok().data("chapter", chapter);
        }
        return Resp.error();
    }

    @PostMapping("updateChapter")
    public Resp updateChapter(@RequestBody Chapter chapter) {
        boolean flag = this.chapterService.updateById(chapter);
        if (flag) {
            return Resp.ok();
        }
        return Resp.error();
    }

    @DeleteMapping("{chapterId}")
    public Resp updateChapter(@PathVariable("chapterId") String chapterId) {
//        先查询章节下的所有小节云资源
        List<Video> videoList = this.videoService.list(new QueryWrapper<Video>().eq("chapter_id", chapterId));
        if (!CollectionUtils.isEmpty(videoList)) {
            List<String> sourceIds = videoList.stream().map(Video::getVideoSourceId).collect(Collectors.toList());
            String sourceIdsString = StringUtils.join(sourceIds, ",");
//            执行删除
            this.vodClient.removeAlyVideo(sourceIdsString);
        }
//        2.再删数据库中数据
        boolean flag = this.chapterService.removeById(chapterId);
        if (flag) {
            return Resp.ok();
        }
        return Resp.error();
    }


}

